#include "TomographRenderWidget.h"
#include "QDebug"

TomographRenderWidget::TomographRenderWidget(BaseRender *renderObject, QWidget *parent ) : BaseRenderWidget( parent ), _renderObject( renderObject )
{
	//ui.setupUi(this);
	setFocusPolicy(Qt::ClickFocus);
	rotateAroundAxis = new Matrix3f();
	//transform();
}

TomographRenderWidget::~TomographRenderWidget()
{

}

BaseRender* TomographRenderWidget::renderObject()
{

	return _renderObject;

}

void TomographRenderWidget::setRenderObject( BaseRender *renderObject )
{

	if( _renderObject != NULL )
		delete _renderObject;

	_renderObject = renderObject;

}

void TomographRenderWidget::mouseMoveEvent( QMouseEvent *event )
{
	GLfloat dx = static_cast< GLfloat >( event->pos().x() - _lastMousePos.x() ) / width () / 0.5 * M_PI;
	GLfloat dy = static_cast< GLfloat >( event->pos().y() - _lastMousePos.y() ) / height() / 0.5 * M_PI;
	
	float cosAlpha;
	float sinAlpha;
	Vector3f axis;
	float x;
	float y;
	float z;
	if (abs(dx) > abs(dy))
	{
		axis = camera()->up();
		x=axis[0];
		y=axis[1];
		z=axis[2];
		cosAlpha = cos(dx*(-1));
		sinAlpha = sin(dx*(-1));

	}
	else 
	{
		axis = camera()->right();
		x=axis[0];
		y=axis[1];
		z=axis[2];
		cosAlpha = cos(dy*(-1));
		sinAlpha = sin(dy*(-1));
	}

	(*rotateAroundAxis) << cosAlpha+(1-cosAlpha)*x*x, (1-cosAlpha)*x*y-sinAlpha*z, (1-cosAlpha)*x*z + sinAlpha*y,
						(1-cosAlpha)*x*y+sinAlpha*z, cosAlpha+(1-cosAlpha)*y*y,  (1-cosAlpha)*y*z - sinAlpha*x,
						(1-cosAlpha)*z*x-sinAlpha*y, (1-cosAlpha)*z*y+sinAlpha*x, cosAlpha+(1-cosAlpha)*z*z;
	if(event->buttons() & Qt::LeftButton)
	{
		camera()->setPosition(*rotateAroundAxis*camera()->position());
		transform.linear() = *rotateAroundAxis;
		camera()->setTransform(transform);
	}
	 qDebug() << "TomographRenderWidget::position: " << camera()->position()[0] << ", "<< camera()->position()[1] << ", "<< camera()->position()[2];
	 //qDebug() << "TomographRenderWidget::view: " << camera()->view()[0] << ", "<< camera()->view()[1] << ", "<< camera()->view()[2];
	 // qDebug() << "TomographRenderWidget::side: " << camera()->right()[0] << ", "<< camera()->right()[1] << ", "<< camera()->right()[2];
	 //qDebug() << "TomographRenderWidget::up: " << camera()->up()[0] << ", "<< camera()->up()[1] << ", "<< camera()->up()[2];
	_lastMousePos = event->pos();
}

void TomographRenderWidget::wheelEvent( QWheelEvent *event )
{                         
	GLfloat delta = static_cast< GLfloat >( event->delta() ) / 10;
	camera()->translate( Vector3f( delta, delta, delta ));
	qDebug() << "TomographRenderWidget::position wheelEvent: " << camera()->position()[0] << ", "<< camera()->position()[1] << ", "<< camera()->position()[2];
}


//void TomographRenderWidget::keyPressEvent ( QKeyEvent *e )
//{
//	int a;
//	a = 1;
//}